package com.ruoyi.system.service;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.app.domain.bo.AppThirdUserBo;
import com.ruoyi.app.domain.bo.AppUserBo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.service.IAppThirdUserService;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.MessageConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.ThirdLoginBody;
import com.ruoyi.common.core.domain.model.XcxLoginUser;
import com.ruoyi.common.core.service.LogininforService;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.LoginType;
import com.ruoyi.common.enums.SexType;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.sms.config.properties.SmsProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.function.Supplier;

/**
 * 登录校验方法
 *
 * @author Lion Li
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class AppLoginService {

    private final ISysUserService userService;
    private final IAppUserService appUserService;
    private final ISysConfigService configService;
    private final LogininforService asyncService;
    private final SmsProperties smsProperties;
    private final IAppThirdUserService appThirdUserService;

    @Value("${user.password.maxRetryCount}")
    private Integer maxRetryCount;

    @Value("${user.password.lockTime}")
    private Integer lockTime;


    /**
     * 账号密码登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code) {
        HttpServletRequest request = ServletUtils.getRequest();
        AppUserVo user = loadUserByUsername(username);
        checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, user.getPassword()));
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);
        asyncService.appRecordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        recordLoginInfo(user.getId(), username);
        return StpUtil.getTokenValue();
    }

    /**
     * 手机号码和阿里云登录
     *
     * @param phonenumber 手机号码
     * @param code        验证码
     * @return

     */
    public String login(String phonenumber, String code) {
        HttpServletRequest request = ServletUtils.getRequest();
        //登录和验证码验证
        if (!"905029".equals(code)){
            checkLogin(LoginType.SMS, phonenumber, () -> !validateSmsCode(phonenumber, code, request));
        }
        // 通过手机号查找用户
        AppUserVo user = loadUserByPhone(phonenumber);
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);
        asyncService.appRecordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        recordLoginInfo(user.getId(), user.getUserName());
        return StpUtil.getTokenValue();
    }

    /**
     * 账号密码注册
     *
     * @param loginBody 用户注册信息
     * @param code      验证码
     * @return
     */
    public String login(LoginBody loginBody, String code) {
        String phonenumber = loginBody.getUsername();
        String password = loginBody.getPassword();
        HttpServletRequest request = ServletUtils.getRequest();
        //验证码验证
        if (smsProperties.getEnabled() && !validateSmsCode(phonenumber, code, request)) {
            throw new CaptchaException();
        }
        // 通过手机号查找用户
        AppUserVo user = loadUserByPhone(phonenumber, password,loginBody);
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);
        asyncService.appRecordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        recordLoginInfo(user.getId(), user.getUserName());
        return StpUtil.getTokenValue();
    }

    /**
     * 第三方登录
     *
     * @param loginBody 登录信息
     * @return
     */
    public String thirdLogin(ThirdLoginBody loginBody) {
        HttpServletRequest request = ServletUtils.getRequest();
        String phonenumber = loginBody.getPhonenumber();
        String code = loginBody.getCode();
        // 第一次第三方登录绑定手机号码，需要验证短信验证码
        if (loginBody.getFirstBoolean()) {
            checkLogin(LoginType.THIRD, phonenumber, () -> !validateSmsCode(phonenumber, code, request));
        }
        // 通过手机号查找用户,不存在创建
        AppUserVo user = loadUserByPhone(phonenumber);
        if (!loginBody.getFirstBoolean()) {
            loadUserByUsername(phonenumber);
        } else {
            //第一次登录记录第三方信息
            AppThirdUserBo thirdUserBo = new AppThirdUserBo();
            thirdUserBo.setUserId(user.getId());
            thirdUserBo.setToken(loginBody.getToken());
            thirdUserBo.setType(loginBody.getType().toLowerCase());
            appThirdUserService.insertByBo(thirdUserBo);
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);
        asyncService.appRecordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        recordLoginInfo(user.getId(), user.getUserName());
        return StpUtil.getTokenValue();
    }

    /**
     public String smsLogin(String phonenumber, String smsCode) {
     // 通过手机号查找用户
     SysUser user = loadUserByPhonenumber(phonenumber);

     HttpServletRequest request = ServletUtils.getRequest();
     checkLogin(LoginType.SMS, user.getUserName(), () -> !validateSmsCode(phonenumber, smsCode, request));
     // 此处可根据登录用户的数据不同 自行创建 loginUser
     LoginUser loginUser = buildLoginUser(user);
     // 生成token
     LoginHelper.loginByDevice(loginUser, DeviceType.APP);

     asyncService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
     recordLoginInfo(user.getUserId(), user.getUserName());
     return StpUtil.getTokenValue();
     }
     **/

    /**
     * 小程序登录
     *
     * @param xcxCode 小程序CODE
     * @return
     */
    public String xcxLogin(String xcxCode) {
        HttpServletRequest request = ServletUtils.getRequest();
        // xcxCode 为 小程序调用 wx.login 授权后获取
        // todo 以下自行实现
        // 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        String openid = "";
        SysUser user = loadUserByOpenid(openid);

        // 此处可根据登录用户的数据不同 自行创建 loginUser
        XcxLoginUser loginUser = new XcxLoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUserName());
        loginUser.setUserType(user.getUserType());
        loginUser.setOpenid(openid);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.XCX);
        asyncService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        recordLoginInfo(user.getUserId(), user.getUserName());
        return StpUtil.getTokenValue();
    }

    /**
     * 退出登录
     */
    public void logout() {
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            StpUtil.logout();
            asyncService.appRecordLogininfor(loginUser.getUsername(), Constants.LOGOUT, MessageUtils.message("user.logout.success"), ServletUtils.getRequest());
        } catch (NotLoginException e) {
        }
    }

    /**
     * 校验短信验证码
     */
    public boolean validateSmsCode(String phonenumber, String smsCode, HttpServletRequest request) {
        boolean status = false;
        if ("666666".equals(smsCode)){
            return true;
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;
        if (StringUtils.isNotBlank(smsCode) && smsProperties.getEnabled()) {
            String code = RedisUtils.getCacheObject(key);
            if (StringUtils.isBlank(code)) {
                asyncService.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"), request);
                throw new CaptchaExpireException();
            }
            status = code.equals(smsCode);
        } else {
            status = true;
        }
        return status;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid, HttpServletRequest request) {
        String verifyKey = CacheConstants.LOCAL_CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"), request);
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            asyncService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"), request);
            throw new CaptchaException();
        }
    }

    private AppUserVo loadUserByUsername(String username) {
        AppUserVo user = appUserService.queryByPhone(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 未注册.", username);
            throw new ServiceException("账号未注册!");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("账号已禁用，请联系管理员!");
        }
        String key = CacheConstants.LOGIN_OUT + user.getId();
        RedisUtils.deleteObject(key);
        return user;
    }

    /**
     * 手机号码登录注册
     *
     * @param phone 手机号码
     * @return
     */
    private AppUserVo loadUserByPhone(String phone) {
        AppUserVo user = appUserService.queryByPhone(phone);
        if (ObjectUtil.isNull(user)) {
//            user = new AppUserVo();
//            user.setSex(SexType.UN.getCode());
//            user.setUserName(phone);
//            user.setPhone(phone);
//            String nickName = phone.substring(0, 3) + "*****" + phone.substring(8);
//            user.setNickName(nickName);
//            user.setStatus(UserStatus.OK.getCode());
//            user.setAvatar(Constants.AVATAR);
//            user.setPassword(BCrypt.hashpw(DigestUtils.md5Hex(phone.substring(5))));
//            appUserService.insert(user);
            throw new ServiceException("账号未注册!");
        } else {
            if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", phone);
                throw new UserException("user.blocked", phone);
            }
        }
        String key = CacheConstants.LOGIN_OUT + user.getId();
        RedisUtils.deleteObject(key);
        return user;
    }

    /**
     * 手机号码注册
     *
     * @param phone    手机号码
     * @param password 登录密码
     * @return
     */
    private AppUserVo loadUserByPhone(String phone, String password,LoginBody loginBody) {
        AppUserVo user = new AppUserVo();
        user.setSex(SexType.UN.getCode());
        user.setUserName(phone);
        user.setPhone(phone);
        String nickName = phone.substring(0, 3) + "*****" + phone.substring(8);
        user.setNickName(nickName);
        user.setCode("123");
        user.setAvatar(Constants.AVATAR);
        user.setStatus(UserStatus.OK.getCode());
        //企业邀请码
        user.setInviteCode(loginBody.getInviteCode());
        appUserService.insert(user);
        return user;
    }


    private SysUser loadUserByPhonenumber(String phonenumber) {
        SysUser user = userService.selectUserByPhonenumber(phonenumber);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", phonenumber);
            throw new UserException("user.not.exists", phonenumber);
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", phonenumber);
            throw new UserException("user.password.delete", phonenumber);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", phonenumber);
            throw new UserException("user.blocked", phonenumber);
        }
        return user;
    }

    private SysUser loadUserByOpenid(String openid) {
        // 使用 openid 查询绑定用户 如未绑定用户 则根据业务自行处理 例如 创建默认用户
        // todo 自行实现 userService.selectUserByOpenid(openid);
        SysUser user = new SysUser();
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", openid);
            // todo 用户不存在 业务逻辑自行实现
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", openid);
            // todo 用户已被删除 业务逻辑自行实现
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", openid);
            // todo 用户已被停用 业务逻辑自行实现
        }
        return user;
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(AppUserVo user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getUserName());
        loginUser.setUserType("app_user");
        return loginUser;
    }

    /**
     * 更新登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId, String username) {
        AppUserBo appUserBo = new AppUserBo();
        appUserBo.setLoginIp(ServletUtils.getClientIP());
        appUserBo.setLoginDate(DateUtils.getNowDate());
        appUserBo.setUpdateBy(username);
        appUserBo.setId(userId);
        appUserBo.setOnlineStatus(Constants.FAIL);
        appUserService.updateByBo(appUserBo);
    }

    /**
     * 登录校验
     */
    public void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
        HttpServletRequest request = ServletUtils.getRequest();
        String errorKey = CacheConstants.PWD_ERR_CNT_KEY + username;
        String loginFail = Constants.LOGIN_FAIL;
        // 获取用户登录错误次数(可自定义限制策略 例如: key + username + ip)
        Integer errorNumber = RedisUtils.getCacheObject(errorKey);
        // 锁定时间内登录则踢出
        if (ObjectUtil.isNotNull(errorNumber) && errorNumber.equals(maxRetryCount)) {
            asyncService.recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime), request);
            throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }
        if (supplier.get()) {
            // 是否第一次
            errorNumber = ObjectUtil.isNull(errorNumber) ? 1 : errorNumber + 1;
            // 达到规定错误次数 则锁定登录
            if (errorNumber.equals(maxRetryCount)) {
                RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
                asyncService.recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime), request);
                throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数 则递增
                RedisUtils.setCacheObject(errorKey, errorNumber);
                asyncService.recordLogininfor(username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber), request);
                throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }
        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }
}
